package com.jn.web;

import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.jn.entity.account.User;
import com.jn.service.account.AccountService;
import com.jn.service.account.ShiroDbRealm.ShiroUser;

/**
 * @ClassName ProfileController
 * @Description 用户修改自己资料的Controller
 * @author liuxd
 * @date 2013年8月27日 上午10:58:14
 * 
 */
@Controller
// 声明该类为控制层
@RequestMapping(value = "/profile")
// value值为该控制器可以拦截的url，如本例可以拦截/task/*的所有请求
public class ProfileController {

	/**
	 * @Fields accountService 使用@Autowired标签注入accountService
	 */
	@Autowired
	private AccountService accountService;

	@RequestMapping(method = RequestMethod.GET)
	public String updateForm(Model model) {
		Long id = getCurrentUserId();
		model.addAttribute("user", accountService.getUser(id));
		return "account/profile";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("user") User user) {
		accountService.updateUser(user);
		updateCurrentUserName(user.getName());
		// 如果为redirect:类似返回值,则springmvc会将页面重定向为后面的地址
		return "redirect:/";
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getUser(
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		if (id != -1) {
			model.addAttribute("user", accountService.getUser(id));
		}
	}

	/**
	 * @Title getCurrentUserId
	 * @Description 取出Shiro中的当前用户Id
	 * @return
	 * @throws
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}

	/**
	 * @Title updateCurrentUserName
	 * @Description 更新Shiro中当前用户的用户名
	 * @param userName
	 * @throws
	 */
	private void updateCurrentUserName(String userName) {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		user.name = userName;
	}
}
